/**
 * Mar 3, 2014 - 11:50:27 AM
 */
package elitech.vietnam.myfashion.widgets;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import elitech.vietnam.myfashion.R;

/**
 * @author Cong Vo
 *
 */
public class ExTextView extends LinearLayout implements View.OnClickListener {
	
	TextView mTextView;
	TextView mViewMore;
	
	String mText = "";
	String mText1 = "";
	int maxLength = 25;
	String textViewMore = "...";
	String textViewLess = "...";
	boolean isCollapsed = false;
	
	public ExTextView(Context context, AttributeSet attrs) {
		super(context, attrs);
		
		LayoutInflater inflater = LayoutInflater.from(context);
		inflater.inflate(R.layout.expandable_textview, this);
		
		mTextView = (TextView) findViewById(R.id.ex_textview);
		mViewMore = (TextView) findViewById(R.id.ex_viewmore);
		
		TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ExTextView);
		maxLength = typedArray.getInt(R.styleable.ExTextView_maxLength, 80);
		textViewMore = typedArray.getString(R.styleable.ExTextView_textViewMore);
		textViewLess = typedArray.getString(R.styleable.ExTextView_textViewLess);
		typedArray.recycle();
		
		mViewMore.setText(textViewMore);
		mViewMore.setPaintFlags(mViewMore.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
		mViewMore.setOnClickListener(this);
	}

	public void setText(String text) {
		mText = text;
		mText1 = getTrimmedText(text);
		mTextView.setText(mText);
		if (mText.length() > mText1.length()) {
			setCollapsed(isCollapsed = true);
			mViewMore.setVisibility(View.VISIBLE);
		}
	}
	

    private String getTrimmedText(String string) {
    	if (string.length() <= maxLength)
    		return string;
    	String result = string.substring(0, maxLength);
		if (string.charAt(maxLength) != ' ' && result.lastIndexOf(" ") > 0) {
			result = result.substring(0, result.lastIndexOf(" "));
		}
		return result + "...";
    }
 

	@Override
	public void onClick(View v) {
		if (v.getId() == mViewMore.getId())
			setCollapsed(!isCollapsed);
	}

	private void setCollapsed(boolean collapsed) {
		if (mText.equals(""))
			throw new IllegalArgumentException("Must call setText first");
		
		isCollapsed = collapsed;
		if (isCollapsed) {
			mViewMore.setText(textViewMore);
			mTextView.setText(mText1);
		} else {
			mViewMore.setText(textViewLess);
			mTextView.setText(mText);
		}
	}
}
